package com.ncloud.crm.service.impl;

import java.util.Date;
import java.util.List;

import com.ncloud.crm.service.WorkNodeService;
import com.ncloud.param.service.SequenceService;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ncloud.common.enmus.ResultEnum;
import com.ncloud.common.exception.UserException;
import com.ncloud.crm.common.Constant;
import com.ncloud.crm.entity.order.OrderContract;
import com.ncloud.crm.mapper.OrderContractMapper;
import com.ncloud.crm.service.OrderContractService;
import com.ncloud.crm.utils.DateUtils;
import com.ncloud.crm.utils.OrderNodeDefineUtils;
import com.ncloud.crm.utils.TableIdDefineUtils;

@Service
public class OrderContractServiceImpl implements OrderContractService {
	
	private static final Logger logger = LogManager.getLogger(OrderContractServiceImpl.class);
	
	@Autowired
	private OrderContractMapper orderContractMapper;
	@Reference
	private SequenceService sequenceService;
	@Autowired
	private WorkNodeService workNodeService;

	public List<OrderContract> getByOrderId(Long orderId){
		List<OrderContract> orderContracts = orderContractMapper.getContractByOrderId(orderId);
		return orderContracts;
	}

	@Override
	public JSONObject getPk(JSONObject json) {
		return null;
	}

	@Override
	public JSONObject insert(JSONObject json) {

		OrderContract orderContract = JSON.parseObject(json.toJSONString(),OrderContract.class);
		try {
			validation(orderContract);
			orderContractMapper.insertOrderContract(orderContract);
		}catch (RuntimeException e){
			e.printStackTrace();
			throw new UserException(ResultEnum.DATABASE_ERROR);
		}
		return json;
	}

	@Override
	public JSONObject validate(JSONObject json, JSONObject result) {
		JSONObject returnJson = new JSONObject();
		JSONArray contractArray = new JSONArray();
		Date currentDate = new Date();
		if(json == null){
			throw new UserException(ResultEnum.ORDER_INFO_ERROR);
		}
		if(json.containsKey(OrderNodeDefineUtils.ORDER_CONTRACT)){
			JSONArray contractInfos = json.getJSONArray(OrderNodeDefineUtils.ORDER_CONTRACT);
			for(int i=0;i<contractInfos.size();i++){
				JSONObject contractInfo = contractInfos.getJSONObject(i);
				OrderContract orderContract = JSON.parseObject(contractInfo.toJSONString(),OrderContract.class);
				String modifyTag = orderContract.getModifyTag();
				//*处理orderId*//*
				if(orderContract.getOrderId() == null){
					if(!result.containsKey(TableIdDefineUtils.ORDER_ID) || StringUtils.isEmpty(result.getString(TableIdDefineUtils.ORDER_ID))){
						throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"订单合同信息orderId不存在！");
					}else{
						orderContract.setOrderId(result.getLong(TableIdDefineUtils.ORDER_ID));
					}
				}

				/*处理custId*/
				if(orderContract.getCustId() == null){
					if(!result.containsKey(TableIdDefineUtils.CUST_ID) || StringUtils.isEmpty(result.getString(TableIdDefineUtils.CUST_ID))){
						if(modifyTag.equals(Constant.ADD)){
							throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"订单合同信息orderId不存在！");
						}
						throw new UserException(ResultEnum.ORDER_INFO_ERROR);
					}else{
						orderContract.setCustId(result.getLong(TableIdDefineUtils.CUST_ID));
					}
				}
				if(orderContract.getSaleId() == null){
					orderContract.setSaleId(json.getLong("userId"));
				}
				if(Constant.ADD.equals(modifyTag)){
					//*生成合同实例编码*//
					Long id = sequenceService.getSequence("seq_contract_inst_id");
					result.put(TableIdDefineUtils.CONTRACT_ID,id);
					orderContract.setContractId(id);
					orderContract.setSignDate(currentDate);
					orderContract.setExpDate(DateUtils.parseDate(Constant.END_DATE));
					orderContract.setCreateTime(currentDate);
					orderContract.setCreateUser(json.getLong("userId"));
				}else if(Constant.UPDATE.equals(modifyTag)){
					//orderContract.setExpDate(currentDate);
				}else if(Constant.DEL.equals(modifyTag)){

				}else {

				}
				contractArray.add(orderContract);
			}
			returnJson.put(OrderNodeDefineUtils.ORDER_CONTRACT,contractArray);
		}
		return returnJson;
	}
/*@Override
	public JSONObject validate(JSONObject json,JSONObject result) {
		JSONObject returnJson = new JSONObject();
		*//*begin*//*
		JSONArray nodeArray = new JSONArray();
		JSONArray nodeEqptArray = new JSONArray();
		JSONArray nodePublicCloudArray = new JSONArray();
		JSONArray nodeInterArray = new JSONArray();
		JSONArray workArray = new JSONArray();
		JSONArray nodeItemArray = new JSONArray();
		JSONArray contractNodeArray = new JSONArray();
		*//*end*//*
		JSONArray contractArray = new JSONArray();
		if(json == null){
			throw new UserException(ResultEnum.ORDER_INFO_ERROR);
		}
		if(json.containsKey(OrderNodeDefineUtils.ORDER_CONTRACT)){
			JSONArray contractInfos = json.getJSONArray(OrderNodeDefineUtils.ORDER_CONTRACT);
			for(int i=0;i<contractInfos.size();i++){
				JSONObject contractInfo = contractInfos.getJSONObject(i);
				String modifyTag = contractInfo.getString("modifyTag");

				if(Constant.ADD.equals(modifyTag)){
					*//*生成合同实例编码*//*
					if(!contractInfo.containsKey(TableIdDefineUtils.CONTRACT_ID) || StringUtils.isEmpty(contractInfo.getString(TableIdDefineUtils.CONTRACT_ID))){
						Long id = sequenceService.getSequence("seq_contract_inst_id");
						contractInfo.put(TableIdDefineUtils.CONTRACT_ID,id);
						result.put(TableIdDefineUtils.CONTRACT_ID,id);
						contractInfo.put(TableIdDefineUtils.CHILD_CONTRACT_ID,id);
						result.put(TableIdDefineUtils.CHILD_CONTRACT_ID,id);
					}else{
						Long id = sequenceService.getSequence("seq_contract_inst_id");
						result.put(TableIdDefineUtils.CONTRACT_ID,id);
						contractInfo.put(TableIdDefineUtils.CHILD_CONTRACT_ID,id);
						result.put(TableIdDefineUtils.CHILD_CONTRACT_ID,id);
					}
				}else if(Constant.UPDATE.equals(modifyTag)){
					contractInfo.put("modifyTag",Constant.ADD);
					Long id = sequenceService.getSequence("seq_contract_inst_id");
					contractInfo.put(TableIdDefineUtils.CHILD_CONTRACT_ID,id);
					result.put(TableIdDefineUtils.CHILD_CONTRACT_ID,id);
					result.put(TableIdDefineUtils.CONTRACT_ID,contractInfo.getString(TableIdDefineUtils.CONTRACT_ID));
				}else if(Constant.DEL.equals(modifyTag)){
					contractInfo.put("updateTime",DateUtils.getDateTime());
					contractInfo.put("updateUser",json.getLong("userId"));
					contractInfo.put("remark","合同解除");
					result.put(TableIdDefineUtils.CHILD_CONTRACT_ID,contractInfo.getString(TableIdDefineUtils.CHILD_CONTRACT_ID));
					result.put(TableIdDefineUtils.CONTRACT_ID,contractInfo.getString(TableIdDefineUtils.CONTRACT_ID));
				}else {
					contractInfo.put("updateTime",DateUtils.getDateTime());
					contractInfo.put("updateUser",json.getLong("userId"));
					contractInfo.put("remark",modifyTag);
					result.put(TableIdDefineUtils.CHILD_CONTRACT_ID,contractInfo.getString(TableIdDefineUtils.CHILD_CONTRACT_ID));
					result.put(TableIdDefineUtils.CONTRACT_ID,contractInfo.getString(TableIdDefineUtils.CONTRACT_ID));
				}

				*//*处理orderId*//*
				if(!contractInfo.containsKey(TableIdDefineUtils.ORDER_ID) || StringUtils.isEmpty(contractInfo.getString(TableIdDefineUtils.ORDER_ID))){
					if(!result.containsKey(TableIdDefineUtils.ORDER_ID) || StringUtils.isEmpty(result.getString(TableIdDefineUtils.ORDER_ID))){
						if(modifyTag.equals("1")){
							throw new UserException(ResultEnum.PARAM_ERROR.getCode(),"订单客户信息orderId不存在！");
						}
						throw new UserException(ResultEnum.ORDER_INFO_ERROR);
					}else{
						contractInfo.put(TableIdDefineUtils.ORDER_ID,result.getString(TableIdDefineUtils.ORDER_ID));
					}
				}
				//处理项目id
				if(!contractInfo.containsKey(TableIdDefineUtils.PROJECT_ID) || StringUtils.isEmpty(contractInfo.getString(TableIdDefineUtils.PROJECT_ID))){
					if (!result.containsKey(TableIdDefineUtils.PROJECT_ID) || StringUtils.isEmpty(result.getString(TableIdDefineUtils.PROJECT_ID))) {
						throw new UserException(ResultEnum.PARAM_ERROR.getCode(), "订单合同信息projectId不存在！");
					} else {
						contractInfo.put(TableIdDefineUtils.PROJECT_ID, result.getString(TableIdDefineUtils.PROJECT_ID));
					}
				}
				*//*处理orderId*//*
				if(!contractInfo.containsKey("saleId") || StringUtils.isEmpty(contractInfo.getString("saleId"))){
					contractInfo.put("saleId", json.getLong("userId"));
				}
				//设置人员
				contractInfo.put("createUser",json.getLong("userId"));
				//设置创建时间
				contractInfo.put("createTime", result.getString("createTime")!=null?result.getString("createTime"): DateUtils.getDateTime());
				OrderContract orderContract = JSON.parseObject(contractInfo.toJSONString(),OrderContract.class);
				*//*处理完的项目保存*//*
				contractArray.add(JSON.parseObject(JSON.toJSONString(orderContract)));

				*//***********调用合同节点信息********************//*
				JSONObject nodeInfos = workNodeService.validate(contractInfo,result);
				nodeArray.addAll(nodeInfos.getJSONArray(OrderNodeDefineUtils.NODE));
				nodeEqptArray.addAll(nodeInfos.getJSONArray(OrderNodeDefineUtils.NODE_EQPT));
				nodePublicCloudArray.addAll(nodeInfos.getJSONArray(OrderNodeDefineUtils.NODE_PUBLIC_CLOUD));
				nodeInterArray.addAll(nodeInfos.getJSONArray(OrderNodeDefineUtils.NODE_INTER));
				workArray.addAll(nodeInfos.getJSONArray(OrderNodeDefineUtils.WORK));
				nodeItemArray.addAll(nodeInfos.getJSONArray(OrderNodeDefineUtils.NODE_ITEM));
				contractNodeArray.addAll(nodeInfos.getJSONArray(OrderNodeDefineUtils.CONTRACT_NODE));
				returnJson.putAll(workNodeService.validate(contractInfo,result));
				*//***********调用合同节点信息end********************//*
			}
			returnJson.put(OrderNodeDefineUtils.ORDER_CONTRACT,contractArray);
			//节点信息
			returnJson.put(OrderNodeDefineUtils.NODE,nodeArray);
			//组装cpe设备
			returnJson.put(OrderNodeDefineUtils.NODE_EQPT,nodeEqptArray);
			//组装公有云设备
			returnJson.put(OrderNodeDefineUtils.NODE_PUBLIC_CLOUD,nodePublicCloudArray);
			//组装isp
			returnJson.put(OrderNodeDefineUtils.NODE_INTER,nodeInterArray);
			//组装work
			returnJson.put(OrderNodeDefineUtils.WORK,workArray);
			//组装属性节点信息
			returnJson.put(OrderNodeDefineUtils.NODE_ITEM,nodeItemArray);
			//合同节点关系信息
			returnJson.put(OrderNodeDefineUtils.CONTRACT_NODE,contractNodeArray);
			logger.info("订单合同信息:{}"+contractArray.toJSONString());
		}
		return returnJson;
	}*/

	private void validation(OrderContract account){

	}
}
